package com.business.system.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.business.system.bean.GoodsOrdersBean;
import net.sf.rose.jdbc.DBUtils;
import net.sf.rose.jdbc.KeyGenerator;
import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.StringUtil;
import net.sf.rose.web.utils.WebUtils;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.business.system.bean.GoodsBean;
import com.business.system.bean.GoodsStoreBean;
import com.business.system.util.DBTools;
import com.business.system.util.FileUtil;
import com.business.system.util.PageUtil;

/**
 * @Description:商品处理
 * @author: zhangqiang
 * @Date: 8:49 2018/4/17
 */
@RestController
@RequestMapping("goods")
public class GoodsAction {


    /**
     * 获取全部商品
     * @param service
     * @param request
     * @return
     */
    @RequestMapping("list.do")
    public List<Map<String, Object>> list(Service service, HttpServletRequest request){
        StringBuilder sql = new StringBuilder();
        sql.append("select t1.*,t2.BRAND_NAME,t3.STOCK_COUNT from goods t1 left join brand t2 on t1.BRAND_ID = t2.ID LEFT JOIN goods_store t3 on t1.ID = t3.GOODS_ID where 1=1");
        return DBTools.getDataList(service, sql.toString());

    }



    /**
     * @Description:获取商品，分页
     * @Author: zhangqiang
     * @Date: 16:16 2018/4/14
     */
    @RequestMapping("getGoodsListByPage.do")
    public PageBean getGoodsListByPage(Service service, HttpServletRequest request) {
        PageBean page = PageUtil.page(request);
        StringBuilder sql = new StringBuilder();
        sql.append("select t1.*,t2.BRAND_NAME from goods t1 left join brand t2 on t1.BRAND_ID = t2.ID where 1=1");
        Map<String, Object> params = WebUtils.getRequestData(request);
        if (params.containsKey("content")) {
            sql.append(" and (t1.GOODS_NAME like '%" + params.get("content") + "%' or t1.GOODS_NO like '%"+params.get("content")+"%' )");
        }

        if (params.containsKey("brand")) {
            sql.append(" and t1.BRAND_ID = '"+params.get("brand")+"'");
        }

        DBTools.getDataList(service, sql.toString(), page);
        return page;
    }


    /**
     * @Description:保存商品
     * @Author: zhangqiang
     * @Date: 13:10 2018/4/16
     */
    @RequestMapping("saveGoods.do")
    public int saveGoods(Service service, HttpServletRequest request,GoodsBean goodsBean ) {
        if(StringUtil.isEmpty(goodsBean.getId())){
            goodsBean.setId(KeyGenerator.getSystemUUID());
            Map<String,Object> params = new HashMap<>();
            params.put("goodsNo",goodsBean.getGoodsNo());
            List<GoodsBean> goodsBeanList = DBUtils.getBeanList(service,GoodsBean.class,params);

            if(goodsBeanList.size()>0){
                return 999;  //商品编号不能重复
            }

            //初始化库存为100
            GoodsStoreBean goodsStoreBean = new GoodsStoreBean();
            goodsStoreBean.setId(KeyGenerator.getSystemUUID());
            goodsStoreBean.setGoodsId(goodsBean.getId());
            goodsStoreBean.setStockCount(100);
            DBTools.insertBean(service, goodsStoreBean);

            return  DBTools.insertBean(service, goodsBean);
        }
        else{
            return  DBTools.forceupdateBean(service, goodsBean,"isShelf");
        }

    }


    @RequestMapping(value ="savePicGoods.do",method = RequestMethod.POST)
    public int savePicGoods(Service service, HttpServletRequest request) {
        //额外的数据
        Map<String,Object> data = WebUtils.getRequestData(request);
        GoodsBean goodsBean = new GoodsBean();
        goodsBean.setGoodsNo(data.get("GOODS_NO").toString());
        goodsBean.setGoodsName(data.get("GOODS_NAME").toString());
        goodsBean.setBrandId(data.get("BRAND_ID").toString());
        goodsBean.setGoodsSpec(data.get("GOODS_SPEC").toString());
        goodsBean.setSalePrice(Double.parseDouble(data.get("SALE_PRICE").toString()));
        goodsBean.setCostPrice(Double.parseDouble(data.get("COST_PRICE").toString()));
        goodsBean.setIsShelf(Integer.parseInt(data.get("IS_SHELF").toString()));

        goodsBean.setGoodsImg(data.get("GOODS_IMG")==null?"":data.get("GOODS_IMG").toString());

        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

        //有图片则上传图片
        if(fileMap!=null){
            //额外的数据
            String ctxPath = FileUtil.getUploadFilePath();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            String ymd = sdf.format(new Date());
            ctxPath += File.separator + ymd + File.separator;
            // 创建文件夹
            File file = new File(ctxPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = null;
            UUID uuid = null;
            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
                // 上传文件
                MultipartFile mf = entity.getValue();
                fileName = mf.getOriginalFilename();// 获取原文件名
                fileName = fileName.substring(fileName.lastIndexOf("."));
                uuid = UUID.randomUUID();
                File uploadFile = new File(ctxPath + uuid + fileName);
                try {
                    FileCopyUtils.copy(mf.getBytes(), uploadFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String path = ymd + "/" + uuid + fileName;

            goodsBean.setGoodsImg(path);
            //新增品牌
            if(data.get("ID")==null){
                goodsBean.setId(KeyGenerator.getSystemUUID());

                //初始化库存为100
                GoodsStoreBean goodsStoreBean = new GoodsStoreBean();
                goodsStoreBean.setId(KeyGenerator.getSystemUUID());
                goodsStoreBean.setGoodsId(goodsBean.getId());
                goodsStoreBean.setStockCount(100);
                DBTools.insertBean(service, goodsStoreBean);
                return  DBTools.insertBean(service, goodsBean);
            }
            else{
                goodsBean.setId(data.get("ID").toString());
                return  DBTools.forceupdateBean(service, goodsBean,"isShelf");
            }

        }
        else{
            //更新
            goodsBean.setId(data.get("ID").toString());
            return  DBTools.forceupdateBean(service, goodsBean,"isShelf");
        }

    }


    /**
     * @Description:删除商品
     * @Author: zhangqiang
     * @Date: 14:39 2018/4/16
     */
    @RequestMapping("deleteGoods.do")
    public int deleteBrand(Service service, HttpServletRequest request,GoodsBean goodsBean ) {
        return  DBTools.deleteBean(service, goodsBean);
    }

}